
package com.controller.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class IndexFreeMarkerView extends FreeMarkerView {

	@Override
	protected void doRender(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		exposeModelAsRequestAttributes(model, request);// 查取Model对象
		SimpleHash fmModel = buildTemplateModel(model, request, response);

		if (logger.isDebugEnabled()) {
			logger.debug("Rendering FreeMarker template [" + getUrl() + "] in FreeMarkerView '" + getBeanName() + "'");
		}
		Locale locale = RequestContextUtils.getLocale(request);

		/*
		 * 默认生成静态文件,除非在编写ModelAndView时为false, 这样对静态文件生成的粒度控制更细一点 例如：ModelAndView
		 * mav = new ModelAndView("search"); mav.addObject("CREATE_HTML",
		 * false);
		 */
		if (Boolean.FALSE.equals(true)) {
			processTemplate(getTemplate(locale), fmModel, response);// 调用动态宣染器
		} else {
			createHTML(getTemplate(locale), fmModel, request, response);// 生成静态html
		}
	}

	public void createHTML(Template template, SimpleHash model, HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException, ServletException {

		// 站点根目录的绝对路径
		String requestHTML = this.getRequestHTML(request);
		// 判断文件是否存在
		File htmlFile = new File(requestHTML);
		if (!htmlFile.getParentFile().exists()) {
			htmlFile.getParentFile().mkdirs();// 创建目录
		}
		if (!htmlFile.exists()) {
			htmlFile.createNewFile();// 创建文件
		}
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
		// 处理模版
		template.process(model, out);
		out.flush();
		out.close();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		/* 将请求转发到生成的htm文件 */
		// request.getRequestDispatcher(requestHTML).forward(request, response);
		response.sendRedirect(basePath + "/statics/" + request.getRequestURI() + ".html");
	}

	/**
	 * 计算要生成的静态文件相对路径 因为大家在调试的时候一般在Tomcat的webapps下面新建站点目录的，
	 * 但在实际应用时直接布署到ROOT目录里面,这里要保证路径的一致性。
	 * 
	 * @param request HttpServletRequest
	 * @return /*.html
	 */
	private String getRequestHTML(HttpServletRequest request) {

		String htmlPath = request.getSession().getServletContext().getRealPath("/statics");
		// 生成的文件的名字
		String requestURI = htmlPath + request.getRequestURI() + ".html";

		return requestURI;
	}
}
